<template>
  <div class="app-container box">
    <el-row>
      <el-col :span="24">
        <el-card shadow="never">
          <el-col :span="12" class="container">
            <vue-esign ref="esign" :width="500" :height="300" :isCrop="isCrop"
                       :isClearBgColor="false"
                       :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
            <div class="btn">
              <el-button @click="handleReset">
                清空画布
              </el-button>
              <el-button @click="handleGenerate">
                生成图片
              </el-button>
              <el-button @click="handleDownload">
                下载图片
              </el-button>
            </div>
          </el-col>
          <el-col :span="12" class="container">
              <el-image :src="resultImg" style="width: 500px;height: 300px;">
                  <i class="el-icon-picture-outline"></i>
              </el-image>
          </el-col>
        </el-card>
      </el-col>

    </el-row>
  </div>
</template>

<script>
export default {
  name: 'signature',
  data () {
    return {
      lineWidth: 6,
      lineColor: '#000000',
      bgColor: '#f0f0f0',
      resultImg: '',
      isCrop: false
    }
  },
  methods: {
    handleDownload() {
      if (this.resultImg=='') return;
      let fileName =  new Date().getTime() + ".png";
      this.downloadImage(this.resultImg,fileName)
    },
    downloadImage(imgsrc, name) {
      //下载图片地址和图片名
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据'
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click", {
          bubbles: true,
          cancelable: true,
          view: window
        }); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    },
    handleReset () {
      this.$refs.esign.reset()
    },
    handleGenerate () {
      this.$refs.esign.generate().then(res => {
        this.resultImg = res
        console.log(res)
      }).catch(err => {
        alert(err)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding-bottom: 70px;
  height: calc(100vh - 250px);
  .btn{
    margin-top: 10px;
  }
}
</style>
